package eclasstest;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        //创建对象
        List<Student> list = new ArrayList<>();
        list.add(new Student("张三",20, 80));
        list.add(new Student("lisi",22, 80));
        list.add(new Student("wangwu",21, 100));
        list.add(new Student("zhaoliu",23, 90));
        //使用Compareable接口对四位同学成绩做降序排列
        sort(list);
        System.out.println("根据成绩排序后");
        for (Student student : list) {
            System.out.println(student);
        }
        //用Comparator实现按照姓名排序，请正确指定泛型0
        sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        System.out.println("根据姓名排序后");
        for (Student student : list) {
            System.out.println(student);
        }
    }
    //使用Compareable接口对四位同学成绩做降序排列
    public static <T extends Comparable<T>> void sort(List<T> list){
        for (int i = 0; i < list.size(); i++) {//循环次数
            for (int j = 0; j < list.size()-i-1; j++) {//循环换位
                if (list.get(j).compareTo(list.get(j+1))>0){//比较当前元素和后一个元素大小关系，如果当前元素比后一个元素大，则交换位置
                    T temp = list.get(j);
                    list.set(j,list.get(j+1));
                    list.set(j+1,temp);
                }
            }
        }
    }
    ////用Comparator实现按照姓名排序，请正确指定泛型0
    public static <T> void sort(List<T> list, Comparator<? super T> c){
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < list.size()-i-1; j++) {
                if (c.compare(list.get(j),list.get(j+1))>0){//比较当前元素和后一个元素大小关系，如果当前元素比后一个元素大，则交换位置
                    T temp = list.get(j);
                    list.set(j,list.get(j+1));
                    list.set(j+1,temp);
                }
            }
        }
    }
}

